<template>
  <div class="bg" ref="boxRef">
    <div
      @click="moveEntity"
      class="Anchor"
      :style="{ top: position.y + 'px', left: position.x + 'px' }"
    ></div>

    <div v-if="postList.length > 0">
      <ul>
        <li
          @click="touchMove(index)"
          :style="{ top: item.y + 'px', left: item.x + 'px' }"
          class="post"
          v-for="(item, index) of postList"
        ></li>
      </ul>
    </div>
    <canvas class="webgl" type="webgl" ref="glRef" id="gl"></canvas>
  </div>
</template>

<script>
import * as THREE from 'three';
import { useThreeHooks } from '@/hooks/useThree';
import {
  getBoxHelperEdgeMidpointsOnScreen,
  setupMouseInteraction,
} from './threeUtils';
const {
  threeInfo,
  addEntity,
  render,
  initScance,
  initCamera,
  addLight,
  initGridHelper,
  initAxesHelper,
  initStats,
  initRender,
  initControls,
  clearScene,
  buildObjEntity,
  initRaycaster,
  createBoundingHelper,
  getModelScreenPosition,
} = useThreeHooks();
export default {
  data() {
    return {
      BoxHelperSelect: '',
      selectName: '',
      selectEntity: '',
      position: {
        x: 0,
        y: 0,
        z: 0,
      },
      postList: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  beforeDestroy() {
    clearScene();
  },
  methods: {
    moveEntity() {
      setupMouseInteraction(
        threeInfo.camera,
        threeInfo.scene,
        null,
        intersectionPoint => {
          // this.selectEntity.parent.position.x = intersectionPoint.x;
          // this.selectEntity.parent.position.z = intersectionPoint.z;
          this.selectEntity.parent.position.x = 0;
          this.selectEntity.parent.position.z = 0;
          this.selectEntity.parent.position.y = 10;
        },
        null,
      );
    },
    resetBoxHelperSelect() {
      threeInfo.scene.remove(this.BoxHelperSelect); // 从场景中移除边框帮助器
      this.BoxHelperSelect = createBoundingHelper(this.selectEntity);
      addEntity(this.BoxHelperSelect);
    },
    touchMove(index) {
      setupMouseInteraction(threeInfo.camera, threeInfo.scene);
      // Z：index==0&&3   X：index==1&&2   Y：index==4
      if (index === 0 || index === 3) {
        this.selectEntity.scale.z += 0.1;
        this.selectEntity.position.z += 0.1;
      } else if (index === 1 || index === 2) {
        this.selectEntity.scale.x += 0.1;
        this.selectEntity.position.x += 0.1;
      } else {
        this.selectEntity.scale.y += 1;
        this.selectEntity.position.y += 1;
      }
      this.resetBoxHelperSelect();
    },

    toAddAnchor() {
      if (this.BoxHelperSelect) {
        const selectEntity = threeInfo.meshList.filter(res => {
          return res.name == this.selectName;
        });
        this.position = getModelScreenPosition(selectEntity[0]);
        if (this.BoxHelperSelect) {
          this.postList = getBoxHelperEdgeMidpointsOnScreen(
            this.BoxHelperSelect,
            threeInfo.camera,
          );
        }
      }
    },
    initLight() {
      // 添加环境光
      const mabient = new THREE.AmbientLight(0xffffff, 1);
      mabient.position.set(0, 0, 0);
      addLight(mabient);
    },
    // 创建模型
    createEntity() {
      this.initEarth(1);
    },
    initEarth(Earth_RADIUS = 3.5) {
      buildObjEntity('earth.obj', 'earth.png').then(objectEntity => {
        // objectEntity?.position.set(-10, 5, 0);
        const scaleNum = Earth_RADIUS; //模型大小
        objectEntity?.scale.set(scaleNum, scaleNum, scaleNum);
        objectEntity.name = 'earth';
        const objectEntityMesh = objectEntity?.children[0];
        objectEntityMesh.geometry.center(); //中心点
        addEntity(objectEntity);
      });
      buildObjEntity('earth.obj', 'earth.png').then(objectEntity => {
        objectEntity?.position.set(-10, 5, 0);
        const scaleNum = Earth_RADIUS; //模型大小
        objectEntity?.scale.set(scaleNum, scaleNum, scaleNum);
        objectEntity.name = 'earth2';
        const objectEntityMesh = objectEntity?.children[0];
        objectEntityMesh.geometry.center(); //中心点
        addEntity(objectEntity);
      });
    },

    // 点击回调
    onClickCallBack(list) {
      if (list.length == 0) return;
      threeInfo.scene.remove(this.BoxHelperSelect); // 从场景中移除边框帮助器
      this.BoxHelperSelect = createBoundingHelper(list[0].object);
      this.selectEntity = list[0].object;
      this.selectName = list[0].object.parent.name;
      addEntity(this.BoxHelperSelect);
    },
    // 渲染函数
    toRender() {},
    // =========================================
    async init() {
      // 初始化场景
      await initScance(this.$refs.boxRef, this.$refs.glRef);
      // 初始化相机
      initCamera().then(camera => {
        camera.position.set(-10, 15, 10); //相机位置
        camera.lookAt(0, 0, 0); //相机看相位置
      });
      initGridHelper(20, 20);
      initAxesHelper(); //初始化三维坐标
      initRender(); //初始化渲染器
      // 初始化轨道控制器
      initControls().then(controls => {
        controls.enableDamping = true; //阻尼感
        controls.dampingFactor = 0.05;
      });
      initStats(); //性能监视器
      this.initLight();
      this.createEntity();
      initRaycaster(this.onClickCallBack);
      render(this.toAddAnchor); //渲染函数
    },
  },
};
</script>

<style lang="scss" scoped>
.bg {
  position: relative;
  height: 100vh;
  width: 100vw;
}

.webgl {
  height: 100vh;
  width: 100vw;
}
.Anchor {
  width: 20px;
  height: 20px;
  position: absolute;
  background-image: url('~@/assets/move.webp');
  background-size: 100% 100%;
  transform: translate(-50%, -50%);
  border-radius: 100%;
  cursor: pointer;
}
.Anchor:hover {
  background-color: greenyellow;
}

.post {
  width: 10px;
  height: 10px;
  position: absolute;
  background-image: url('~@/assets/double_scale.webp');
  background-size: 100% 100%;
  transform: translate(-50%, -50%);
  border-radius: 100%;
  cursor: pointer;
}
</style>
